package com.team2.outpatient_sys.filter;

import com.team2.outpatient_sys.util.JwtUtils;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;

@Component
public class LoginFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 获取token请求头
        String token = request.getHeader("token");
        // 获取小程序认证请求头
        String wx = request.getHeader("wxtoken");

        // 判断是否是微信认证登录
        if(wx == null) {
            // 判断请求是否携带token
            if (null == token || ("").equals(token)) {
                // 若没有token，则放行由Spring Security处理，返回错误或转发给login
                filterChain.doFilter(request, response);
                return;
            }

            // 处理无效token
            if (!JwtUtils.verify(token)) {
                throw new RuntimeException("无效的token");
            }
        }

        // 获取权限
        ArrayList<GrantedAuthority> authorities = new ArrayList<>();
        // 暂时默认所有权限，待更新
        authorities = null;

        // token验证通过，提供授权
        Authentication authentication = new UsernamePasswordAuthenticationToken(null, null, authorities);
        SecurityContextHolder.getContext().setAuthentication(authentication);
        filterChain.doFilter(request, response);
    }
}
